package com.test.fundible.fundible_02_permission;

import static com.test.fundible.fundible_00_utils.FundibleUtil.startLoading;
import static com.test.fundible.fundible_00_utils.FundibleUtil.stopLoading;

import static com.test.fundible.fundible_00_utils.FundibleConfigs.PermissionCode_PhoneState;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager2.widget.ViewPager2;

import com.test.fundible.R;
import com.test.fundible.fundible_00_analytics.FundibleUtil.FundibleAnalyticsUtil;
import com.test.fundible.fundible_00_http.OkHttpUtil;
import com.test.fundible.fundible_00_utils.FundibleConfigs;
import com.test.fundible.fundible_00_utils.FundibleUtil;
import com.test.fundible.fundible_00_utils.Kind_fundibleTip_fundibleDialog;
import com.test.fundible.fundible_01_launcher.Base_fundibleApplication;
import com.test.fundible.fundible_03_login.Log_fundibleinInfo;
import com.test.fundible.fundible_03_login.LoginAc_fundibletivity;
import com.test.fundible.fundible_04_home.MainAct_fundibleivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;


public class Permission_fundibleActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks, EasyPermissions.RationaleCallbacks {

    private ViewPager2 viewPager;

    private PermissionAdapter permissionAdapter;

    private final ArrayList<PermissionInfo> permissionInfoList = new ArrayList<>();
    private PermissionInfo applistPermissionInfo,phonestatePermissionInfo;

    private final String TAG = "PERMISSION";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fundible_permission);
        //tag2024
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);

        findViewById(R.id.afp_ib_back).setOnClickListener(v -> onBackPressed());

        viewPager = findViewById(R.id.afp_viewpage);

        initPermissionInfoList();
    }

    private void initPermissionInfoList(){

        permissionInfoList.clear();

        //appList权限
        if (!FundibleUtil.checkStartPermission_fundible(this)){
            applistPermissionInfo = new PermissionInfo(
                    R.drawable.icon_permission_apps,
                    getString(R.string.permission_applist_title_fundible),
                    R.string.permission_applist_text_fundible
            );

            //next点击
            applistPermissionInfo.setNextClickListener(v -> {
                OkHttpUtil.getInstance_fundible().uploadEventPoint(TAG,"APPS_NEXT_CLICK","");
                if (hasNext()) next();
            });
            //deny点击
            applistPermissionInfo.setDenyClickListener(v -> {
                OkHttpUtil.getInstance_fundible().uploadEventPoint(TAG,"APPS_DENY_CLICK","");
                applistPermissionInfo.setPermissionStatus(PermissionStatus.Deny_fundible);
                next();
            });
            //agree点击
            applistPermissionInfo.setAgreeClickListener(v -> {
                OkHttpUtil.getInstance_fundible().uploadEventPoint(TAG,"APPS_AGREE_CLICK","");

                if (applistPermissionInfo.isPermissionCheck()) {
                    applistPermissionInfo.setPermissionStatus(PermissionStatus.Agree_fundible);
                    next();
                }
                else
                    new Kind_fundibleTip_fundibleDialog(this,
                            getString(R.string.kind_tips_permission_check_desc),
                            getString(R.string.ok),
                            () -> {
                                applistPermissionInfo.setPermissionCheck(true);
                                applistPermissionInfo.setPermissionStatus(PermissionStatus.Agree_fundible);
                                next();
                            }
                    ).show();

            });

            permissionInfoList.add(applistPermissionInfo);
        }

        //PhoneState权限
        if (!FundibleUtil.checkPhonestatePermission_fundible(this)){
            phonestatePermissionInfo = new PermissionInfo(
                    R.drawable.icon_permission_phonestate,
                    getString(R.string.permission_phonestate_title_fundible),
                    R.string.permission_phonestate_text_fundible
            );

            //next点击
            phonestatePermissionInfo.setNextClickListener(v -> {
                OkHttpUtil.getInstance_fundible().uploadEventPoint(TAG,"PHONE_STATE_NEXT_CLICK","");
                if (hasNext()) next();
            });
            //deny点击
            phonestatePermissionInfo.setDenyClickListener(v -> {
                OkHttpUtil.getInstance_fundible().uploadEventPoint(TAG,"PHONE_STATE_DENY_CLICK","");
                phonestatePermissionInfo.setPermissionStatus(PermissionStatus.Deny_fundible);
                next();
            });
            //agree点击
            phonestatePermissionInfo.setAgreeClickListener(v -> {
                OkHttpUtil.getInstance_fundible().uploadEventPoint(TAG,"PHONE_STATE_AGREE_CLICK","");

                if (phonestatePermissionInfo.isPermissionCheck())
                    EasyPermissions.requestPermissions(this, getString(R.string.launch_permissions_phonestate_fundible), PermissionCode_PhoneState, Manifest.permission.READ_PHONE_STATE);
                else
                    new Kind_fundibleTip_fundibleDialog(this,
                            getString(R.string.kind_tips_permission_check_desc),
                            getString(R.string.ok),
                            () -> {
                                phonestatePermissionInfo.setPermissionCheck(true);
                                EasyPermissions.requestPermissions(this, getString(R.string.launch_permissions_phonestate_fundible), PermissionCode_PhoneState, Manifest.permission.READ_PHONE_STATE);
                            }
                    ).show();

            });

            permissionInfoList.add(phonestatePermissionInfo);
        }

        permissionAdapter = new PermissionAdapter(this,permissionInfoList);
        viewPager.setAdapter(permissionAdapter);
    }

    private boolean hasNext(){
        return permissionAdapter.getItemCount()>0 && (viewPager.getCurrentItem()<permissionAdapter.getItemCount()-1);
    }

    private void next(){
        int nextIndex = viewPager.getCurrentItem()+1;
        if (nextIndex>=0 && permissionAdapter.getItemCount()>nextIndex) {
            viewPager.setCurrentItem(nextIndex);
            if (permissionAdapter.isPermissionHasHandle(nextIndex)) next();
        }
        else if (FundibleUtil.checkPhonestatePermission_fundible(this)) pass();
        else finish();
    }

    //权限通过
    private void pass(){
        FundibleAnalyticsUtil.INSTANCE.init_fundible(Base_fundibleApplication.getInstant());
        startLoading(this,"");
        OkHttpUtil.getInstance_fundible().fetchLauncherConfig(this::on_fundibleApp_fundibleShow_fundibleInfoResponse);
    }


    private void on_fundibleApp_fundibleShow_fundibleInfoResponse(){

        //自动登录
        if (FundibleUtil.didLogin_fundible()){
            try {
                JSONObject object = new JSONObject();
                object.put("token", FundibleUtil.getToken_fundible());
                object.put("userId", FundibleUtil.getUserId_fundible());
                object.put("type", FundibleConfigs.LOGIN_TYPE_OL_fundibleD);
                object.put("isAdSource", FundibleUtil.getIsAdSource_fundible() ? "YES":"NO");
                Log_fundibleinInfo.par_fundiblese(object);

                FundibleAnalyticsUtil.INSTANCE.saveFirebaseAndFacebookS2SInfo_fundible();
                OkHttpUtil.getInstance_fundible().requestUsPrcs(this::on_fundibleUser_fundibleProcess_fundibleResponse);
                return;
            }catch (JSONException e){
                e.printStackTrace();
            }
        }

        stopLoading();

        Intent intent = new Intent(this, LoginAc_fundibletivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);
        finish();
    }

    private void on_fundibleUser_fundibleProcess_fundibleResponse(){
        stopLoading();
        Intent intent = new Intent(this,MainAct_fundibleivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);
        finish();
    }


//---------------------------------权限处理---------------------------------------------


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode,permissions,grantResults,this);
    }


    //权限同意
    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        switch (requestCode){
            case PermissionCode_PhoneState:
                OkHttpUtil.getInstance_fundible().uploadEventPoint(TAG,"PHONE_STATE_SYSTEM_AGREE_CLICK","");
                if (phonestatePermissionInfo!=null) phonestatePermissionInfo.setPermissionStatus(PermissionStatus.Agree_fundible);
                next();
                break;
        }
    }

    //权限拒绝
    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {

        //永久拒绝处理
        if (EasyPermissions.somePermissionPermanentlyDenied(this,perms)){
            switch (requestCode){
                case PermissionCode_PhoneState:
                    OkHttpUtil.getInstance_fundible().uploadEventPoint(TAG,"PHONE_STATE_AFTER_PERMANENTLY_DENY_CLICK","");
                    break;
            }
            new AppSettingsDialog.Builder(this).build().show();
        }else
            switch (requestCode){
                case PermissionCode_PhoneState:
                    OkHttpUtil.getInstance_fundible().uploadEventPoint(TAG,"PHONE_STATE_SYSTEM_DENY_CLICK","");
                    if (phonestatePermissionInfo!=null) phonestatePermissionInfo.setPermissionStatus(PermissionStatus.Deny_fundible);
                    next();
                    break;
            }
    }

    @Override
    public void onRationaleAccepted(int requestCode) {
        switch (requestCode){
            case PermissionCode_PhoneState:
                OkHttpUtil.getInstance_fundible().uploadEventPoint(TAG,"PHONE_STATE_RATIONALE_ACCEPTED_CLICK","");
                EasyPermissions.requestPermissions(this, getString(R.string.launch_permissions_phonestate_fundible), PermissionCode_PhoneState, Manifest.permission.READ_PHONE_STATE);
                break;
        }
    }

    @Override
    public void onRationaleDenied(int requestCode) {
        switch (requestCode){
            case PermissionCode_PhoneState:
                OkHttpUtil.getInstance_fundible().uploadEventPoint(TAG,"PHONE_STATE_RATIONALE_DENIED_CLICK","");
                break;
        }
    }

}











